#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/7/7 12:13
# @Author : linjinting
# @Project : tableview-model
# @File : checkable_comboBox.py
# @Software: PyCharm

from PySide2.QtCore import Qt, Signal
from PySide2.QtWidgets import QComboBox, QLineEdit, QListView
from PySide2.QtGui import QStandardItemModel, QStandardItem

import time


class TTLLinEdit(QLineEdit):
    clicked = Signal()  # 定义clicked信号

    def mouseReleaseEvent(self, QMouseEvent):
        # print(QMouseEvent)
        if QMouseEvent.button() == Qt.LeftButton:
            self.clicked.emit()  # 发送clicked信号


# class TTLQStandardItem(QStandardItem):
#     def emitDataChanged(self, QMouseEvent):
#         print(QMouseEvent)

class ComboCheckBox(QComboBox):
    def __init__(self, parent=None):
        super(ComboCheckBox, self).__init__(parent)
        # self.selected_row_num = 0
        # self.qCheckBox = []
        # self.activated.disconnect()

        self.qLineEdit = TTLLinEdit()
        self.qLineEdit.setReadOnly(True)
        self.setLineEdit(self.qLineEdit)
        self.qLineEdit.clicked.connect(self.showPopup)
        self.qLineEdit.setText("全选")

        self.qListView = QListView()
        self.m_model = QStandardItemModel(self)
        self.setView(self.qListView)
        self.setModel(self.m_model)

        self._changed = False
        self.m_isSelectAll = False
        self.m_checked_items = list()
        self.m_checked_rows = list()
        # self.currentIndex

        self.view().pressed.connect(self.select_activated)
        # self.activated.connect(self.select_activated)
        self.activated.connect(self.check_select_all)
        self.activated.connect(self.update_lineText)

    def hidePopup(self):
        # if not self.isActivated:
        #     return
        # print('hidePopup-start')
        if not self._changed:
            QComboBox.hidePopup(self)
            # self._changed = True
        # print('hidePopup-end', self._changed)
        self._changed = False  # 设置为非变化状态

    def add_item(self, text, userData=None):
        item = QStandardItem()
        item.setCheckable(True)
        item.setCheckState(Qt.Unchecked)
        item.setData(userData, Qt.UserRole + 1)
        item.setText(text)
        self.m_model.appendRow(item)

    def add_items(self, texts):
        for text in texts:
            self.add_item(text)

    def check_select_all(self):
        all_item = self.m_model.item(0)
        if all_item.checkState() == Qt.Checked:
            if self.m_isSelectAll == 0:
                for index in range(self.count()):
                    self.m_model.item(index).setCheckState(Qt.Checked)
                self.m_isSelectAll = 1

        elif all_item.checkState() == Qt.Unchecked:
            if self.m_isSelectAll == 1:
                for index in range(self.count()):
                    self.m_model.item(index).setCheckState(Qt.Unchecked)

        for index in range(1, self.count()):  # 判断是否是全选的状态，如果不是，全选按钮应该处于未选中的状态
            # if self.m_isSelectAll == 1:
            if self.m_model.item(index).checkState() == Qt.Unchecked:
                all_item.setCheckState(Qt.PartiallyChecked)
                self.m_isSelectAll = 0
                break
        # self.get_select_item()

    def select_activated(self, index):
        # print('select_activated', self._changed, index)
        if isinstance(index, int):
            item = self.m_model.item(index)
        else:
            item = self.m_model.itemFromIndex(index)
        if item is None:
            return
        if item.checkState() == Qt.Checked:
            item.setCheckState(Qt.Unchecked)
        else:
            item.setCheckState(Qt.Checked)
        self._changed = True  # 设置为变化状态

    def get_checked_item(self):
        self.m_checked_items.clear()
        checked_rows = list()
        for index in range(0, self.count()):
            if index == 0:
                continue
            item = self.m_model.item(index)
            if item.checkState() == Qt.Checked:
                self.m_checked_items.append(item)
                checked_rows.append(index)
        return checked_rows

    def update_lineText(self):
        self.get_checked_item()
        if len(self.m_checked_items) == 0:
            self.qLineEdit.setText('全选')
            self.m_model.item(0).setCheckState(Qt.Unchecked)
            return []
        self.qLineEdit.setText(";".join([item.text() for item in self.m_checked_items]))
